﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using WebMatrix.WebData;

namespace DuocThaiBinh.Controllers
{
    public class UserInCuaHangController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        [Authorize(Roles = "Administrator")]
        public void UpdateByUser(int userID, int[] khoIDs)
        {
            var cuaHangs = db.UserInCuaHangs.Where(m => m.UserId == userID);
            if (cuaHangs != null && cuaHangs.Count() > 0)
            {
                foreach (var userInCuaHang in cuaHangs)
                {
                    db.UserInCuaHangs.Remove(userInCuaHang);
                }
            }

            if (khoIDs != null && khoIDs.Length > 0)
            {
                foreach (int khoID in khoIDs)
                {
                    UserInCuaHang userInCuaHang = new UserInCuaHang(userID, khoID);
                    db.UserInCuaHangs.Add(userInCuaHang);
                }
            }

            db.SaveChanges();
        }

        public bool CheckUserInCuaHang(int userID, int cuaHangID)
        {
            var khoes = db.UserInCuaHangs.Where(m => m.UserId == userID && m.CuaHangID == cuaHangID);
            if (khoes != null && khoes.Count() > 0)
            {
                return true;
            }

            return false;
        }

        public List<CuaHang> GetCuaHangsByUserName(string userName)
        {
            if (WebSecurity.IsAuthenticated)
            {
                List<CuaHang> retVal = new List<CuaHang>();
                var user = db.UserProfiles.Find(WebSecurity.GetUserId(userName));
                foreach (var userInCuaHang in user.UserInCuaHangs)
                {
                    retVal.Add(userInCuaHang.CuaHang);
                }

                return retVal;
            }

            return null;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}